package com.pickup.netty.server.session;

import io.netty.channel.Channel;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SessionMemoryImpl implements Session {

    private final Map<String, Channel> usernameChannelMap = new ConcurrentHashMap<>();
    private final Map<Channel, String> channelUsernameMap = new ConcurrentHashMap<>();


    private final Map<String, Map<String,Channel>> channelGroupMap = new ConcurrentHashMap<>();

    // 绑定会话
    @Override
    public void bind(String UserId, Channel channel) {
        usernameChannelMap.put(UserId, channel);
        channelUsernameMap.put(channel, UserId);

    }

    // 解绑会话
    @Override
    public void unbind(Channel channel) {
        String userId = channelUsernameMap.remove(channel);
        usernameChannelMap.remove(userId);

    }
    // 获取会话
    @Override
    public Channel getChannel(String username) {
        return usernameChannelMap.get(username);
    }

    // 绑定聊天组会话
    @Override
    public void bindGroup(String GroupId, String UserId, Channel channel) {
        if (!channelGroupMap.containsKey(GroupId)){
            channelGroupMap.put(GroupId, new ConcurrentHashMap<>());
        }
        Map<String, Channel> stringChannelMap = channelGroupMap.get(GroupId);
        stringChannelMap.put(UserId, channel);
    }

    // 解绑聊天组会话
    @Override
    public void unbindGroup(String GroupId, String UserId) {
        Map<String, Channel> stringChannelMap = channelGroupMap.get(GroupId);
        stringChannelMap.remove(UserId);
    }

    // 获取聊天组会话
    @Override
    public Channel getGroup(String GroupId, String UserId) {
        return channelGroupMap.get(GroupId).get(UserId);
    }

    // 获取聊天组会话
    @Override
    public Map<String, Channel> getAllGroup(String GroupId) {
        return channelGroupMap.get(GroupId);
    }




    @Override
    public String toString() {
        return usernameChannelMap.toString();
    }
}
